package com.ziyun.erp.modules.production.operate;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ziyun.erp.common.e.DeleteEnum;
import com.ziyun.erp.common.e.order.OrderItemStatusEnum;
import com.ziyun.erp.common.e.order.ShipStatusEnum;
import com.ziyun.erp.common.e.production.AllotTypeEnum;
import com.ziyun.erp.common.e.production.FinanceStatusEnum;
import com.ziyun.erp.common.e.production.OrderProductionStatusEnum;
import com.ziyun.erp.common.utils.UserUtils;
import com.ziyun.erp.modules.order.entity.OrderInfoEntity;
import com.ziyun.erp.modules.order.service.ErpOrderAllotRelevanceService;
import com.ziyun.erp.modules.order.service.ErpOrderService;
import com.ziyun.erp.modules.order.service.OrderInfoService;
import com.ziyun.erp.modules.production.entity.ErpOrderItemEntity;
import com.ziyun.erp.modules.production.entity.ErpOrderProductionEntity;
import com.ziyun.erp.modules.production.operate.entity.AllotStateEntity;
import com.ziyun.erp.modules.production.operate.entity.AuditStateEntity;
import com.ziyun.erp.modules.production.operate.entity.LogisticsStateEntity;
import com.ziyun.erp.modules.production.service.ErpOrderItemService;
import com.ziyun.erp.modules.production.service.ErpOrderProductionService;
import io.renren.common.utils.R;
import io.renren.common.utils.SpringContextUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author guizhao
 * @Title: 待生产状态
 * @ProjectName ziyun-service-erp
 * @date 2018-09-08 15:57
 */
public class WaitProducingState implements ErpOrderState {

    private static Logger logger = LoggerFactory.getLogger(WaitProducingState.class);

    private ErpOrderService erpOrderService = SpringContextUtils.getBean("erpOrderService", ErpOrderService.class);
    private OrderInfoService orderInfoService = SpringContextUtils.getBean("orderInfoService", OrderInfoService.class);
    private ErpOrderItemService erpOrderItemService = SpringContextUtils.getBean("erpOrderItemService", ErpOrderItemService.class);
    private ErpOrderProductionService erpOrderProductionService = SpringContextUtils.getBean("erpOrderProductionService", ErpOrderProductionService.class);
    private ErpOrderAllotRelevanceService relevanceService = SpringContextUtils.getBean("erpOrderAllotRelevanceService", ErpOrderAllotRelevanceService.class);

    @Override
    public R audit(AuditStateEntity auditStateEntity) {
        return R.error("不支持操作！");
    }

    @Override
    public R allot(AllotStateEntity allotStateEntity) {
        return R.error("不支持操作！");
    }

    @Override
    public R receive(Integer productionId) {
        return R.error("不支持操作！");
    }

    @Override
    public R addLogistics(LogisticsStateEntity logisticsStateEntity,  String userId, String createName) {
        return R.error("不支持操作！");
    }

    @Override
    public R allotPriceFinish(Integer productionId) {
        return R.error("不支持操作！");
    }

    @Override
    public R cancleAllot(Integer productionId) {
        logger.info("=================WaitProducingState cancleAllot start================");
        logger.info("=================WaitProducingState cancleAllot params：productionId["+ productionId +"]");

        ErpOrderProductionEntity erpOrderProduction = erpOrderProductionService.selectById(productionId);
        String orderNo = erpOrderProduction.getOrderNo();
        String allotType = erpOrderProduction.getAllotType();
        String erpItemId = erpOrderProduction.getErpItemId();
        Integer financeStatus = erpOrderProduction.getFinanceStatus();
        Integer onlineCash = erpOrderProduction.getOnlineCash();
        OrderInfoEntity orderInfo = orderInfoService.selectById(orderNo);
        String shipStatus = orderInfo.getShipStatus();

        // 生产单未审核或财务作废，可删除重新分配
        if (financeStatus.intValue() != FinanceStatusEnum.UN_AUDITED.toInt()
                && financeStatus.intValue() != FinanceStatusEnum.CANCEL.toInt()){
            return R.error("生产单已审核完成！");
        }

        // 取消分配信息（线上订单）
        if (onlineCash.intValue() == 1){
            String productionOrder = erpOrderProduction.getProductionOrder();
            String username = UserUtils.getCurentUser().getUsername();
            R result = orderInfoService.orderInfoInvalid(productionOrder, "取消分配选项", username);
            int code = (int) result.get("code");
            if (code != 0){
                String msg = (String) result.get("msg");
                return R.error(msg);
            }
            relevanceService.cancleAllotInfo(productionId);
        }

        // 取消生产单
        Map<String, Object> updateMap = new HashMap<>();
        updateMap.put("productionStatus", OrderProductionStatusEnum.CANCLE.toInt());
        erpOrderProductionService.updateByMap(updateMap, productionId);

        /**
         * 判断是否订单分配线上后录入的成本信息，此处与添加的线下外协商区分开，
         * 成本的录入和删除不影响订单状态
         */
        if (onlineCash.intValue() == 0){
            int selectCount = erpOrderProductionService.selectCount(new EntityWrapper<>(new ErpOrderProductionEntity())
                    .eq("order_no", orderNo)
                    .eq("online_cash", 1)
                    .ne("production_status", OrderProductionStatusEnum.CANCLE.toInt())
            );
            if (selectCount > 0){
                return R.ok();
            }
        }

        if (StringUtils.equals(allotType, AllotTypeEnum.ORDER.toCode())){
            // 订单发货状态，若已发货，删除分配信息，不改变订单分配状态
            if (StringUtils.equals(shipStatus, ShipStatusEnum.NOT_SHIPPED.toCode())){
                // 订单状态 生产中 =》 待分配
                erpOrderService.cancelOrderAllotInfo(orderNo);
            }
            // 商品状态 生产中 =》 待分配
            List<ErpOrderItemEntity> erpOrderItemList = erpOrderItemService.selectListByErpOrder(orderNo);
            List<Integer> eoItemIds = erpOrderItemList.stream().map(ErpOrderItemEntity::getEoItemId).collect(Collectors.toList());
            updateMap.put("status", OrderItemStatusEnum.UN_ALLOTED.toInt());
            erpOrderItemService.updateBatchByMap(updateMap, eoItemIds);

        }else{
            // 商品状态  所有生产单是否取消分配（生产中 =》 待分配）
            int selectCount = erpOrderProductionService.selectCount(new EntityWrapper<>(new ErpOrderProductionEntity())
                    .eq("erp_item_id", erpItemId)
                    .notIn("production_status", OrderProductionStatusEnum.CANCLE.toInt())
                    .eq("del", DeleteEnum.NOT_DELETE.toInt())
            );
            if (selectCount == 0){
                updateMap.put("status", OrderItemStatusEnum.UN_ALLOTED.toInt());
                erpOrderItemService.updateByMap(updateMap, Integer.valueOf(erpItemId));
            }

            if (StringUtils.equals(shipStatus, ShipStatusEnum.NOT_SHIPPED.toCode())){
                // 订单状态 所有商品是否取消分配（生产中 =》 待分配）
                List<ErpOrderItemEntity> erpOrderItemList = erpOrderItemService.selectListByErpOrder(orderNo);
                long count = erpOrderItemList.stream()
                        .filter(item -> item.getStatus().intValue() != OrderItemStatusEnum.UN_ALLOTED.toInt())
                        .count();
                if (count == 0){
                    erpOrderService.cancelOrderAllotInfo(orderNo);
                }
            }
        }

        logger.info("=================WaitProducingState cancleAllot end==================");
        return R.ok();
    }

}
